package com.gitee.cnlongdb.server.threads.init;

import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gitee.cnlongdb.basic.constant.LongDbConstant;
import com.gitee.cnlongdb.server.connect.LongDbConnect;

/**
 * 系统名称：RemoveHandlerThread.java
 * 模块名称：
 * 模块描述：处理要删除的数据库、表、表中数据
 * 功能列表：
 * 模块作者：ZOUYONG
 * 开发时间：2018年12月5日 下午10:05:48
 * 模块路径：com.gitee.cnlongdb.server.threads.init.RemoveHandlerThread
 * 更新记录：
 */
public class RemoveHandlerThread extends Thread {

	private final Logger logger = (Logger) LoggerFactory.getLogger(RemoveHandlerThread.class);

	private LongDbConnect connect;
	public RemoveHandlerThread(LongDbConnect connect) {
		logger.debug(LongDbConstant.longdbDefaultName + "初始化[删除数据库表及数据监听]...");
		this.connect = connect;
	}
	
	@Override
	public void run() {
		try {
			File dataBaseFile = new File(connect.getDataBaseRootDirectory());
			if(!dataBaseFile.exists()) {
				return;
			}
			File[] files = dataBaseFile.listFiles();
			for (File file : files) {
				// 删除数据库
				if(file.getName().endsWith(LongDbConstant.longdbDeleteFlag)) {
					connect.getRemoveOperator().deleteFile(file);
				}
				else if(file.isDirectory()) {
					// 删除数据库表
					File tableHouse = new File(file.getAbsoluteFile() + File.separator + LongDbConstant.longdbDataBaseHouse);
					if(!tableHouse.exists()) {
						continue;
					}
					File[] tableHouses = tableHouse.listFiles();
					for (File table : tableHouses) {
						if(table.getName().endsWith(LongDbConstant.longdbDeleteFlag)) {
							connect.getRemoveOperator().deleteFile(table);
						}
						else if(table.isDirectory()) {
							// 删除表中数据
							File[] dataHouses = table.listFiles();
							for (File dataHouse : dataHouses) {
								if(dataHouse.getName().endsWith(LongDbConstant.longdbDeleteFlag)) {
									connect.getRemoveOperator().deleteFile(dataHouse);
								}
							}
						}
					}
				}
			}
		} catch(Exception e) {
			logger.debug("处理要删除的数据库、表、表中数据异常啦：" + e.getMessage(), e);
		}
	}
	
}
